package ciyuan.DataManager;

import net.minecraft.nbt.CompoundNBT;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.storage.DimensionSavedDataManager;
import net.minecraft.world.storage.WorldSavedData;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DataManager extends WorldSavedData {

    private static final String NBT_ROOT_TAG_NAME = "CYRPG";

    private final Map<String, CompoundNBT> nbtMap = new ConcurrentHashMap<>();

    public DataManager() {
        super(NBT_ROOT_TAG_NAME);
    }

    public DataManager(String name) {
        super(name);
    }

    public static CompoundNBT getNBT(World world, String key) {
        return get(world).nbtMap.get(key);
    }

    public static void setNbt(World world, String key, CompoundNBT value) {
        get(world).setNbt(key, value);
    }

    private void setNbt(String key, CompoundNBT value) {
        this.nbtMap.put(key, value);
        this.setDirty();
    }

    private static DataManager get(World worldIn) {
        if (!(worldIn instanceof ServerWorld)) {
            throw new RuntimeException("Attempted to get the data from a client world. This is wrong.");
        }

        ServerWorld world = worldIn.getServer().overworld();
        DimensionSavedDataManager storage = world.getDataStorage();
        return storage.computeIfAbsent(DataManager::new, NBT_ROOT_TAG_NAME);
    }

    @Override
    public void load(CompoundNBT nbt) {
        nbt.getAllKeys().forEach(key -> nbtMap.put(key, nbt.getCompound(key)));
    }

    @Override
    public CompoundNBT save(CompoundNBT compound) {
        nbtMap.forEach(compound::put);
        return compound;
    }


}
